package com.updesignsz.admin.mapper;

import com.updesignsz.commom.entity.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * TODO 后台用户
 * Created User: lx
 * Date: 2020/4/28 14:24
 */
@Repository
@Mapper
public interface UserMapper {


    @Select("select * from t_user where username = #{username} and password = #{password}")
    User login(@Param("username") String username, @Param("password") String password);

    @Select("select id as userId, id, username, phone_number, created_date, remark  from t_user order by created_date desc")
    @Results({
            @Result(property = "id", column = "userId"),
            @Result(property = "roles", column = "id", many = @Many(select = "com.updesignsz.admin.mapper.RoleMapper.findRoleByUserId"))
    })
    List<User> listAll();


    @Select("select * from t_user where id = #{id}")
    @Results({
            @Result(property = "roles", column = "id", many = @Many(select = "com.updesignsz.admin.mapper.RoleMapper.findRoleByUserId"))
    })
    User getById(@Param("id") Integer id);

    @Insert({
            "insert into t_user(username, password, phone_number, remark, created_date, updated_date, is_removed) ",
            "values (#{username},#{password},#{phoneNumber},#{remark},NOW(),NOW(),0)"
    })
    @Options(useGeneratedKeys = true, keyColumn = "id")
    void saveUser(User user);

    @Update({"<script>",
            "update t_user <set>",
            "<if test=\"phoneNumber != null\" >phone_number = #{phoneNumber},</if>",
            "<if test=\"password != null\" >password = #{password},</if>",
            "<if test=\"remark != null\" >remark = #{remark},</if>",
            "updated_date = NOW()",
            "</set> where id = #{id}",
            "</script>"
    })
    void updateUser(User user);

    @Delete("delete from t_user where id = #{id}")
    void deleteUser(@Param("id") Integer id);
}
